package com.bdqn.BookManage.servlet;

import com.bdqn.BookManage.view.BookInfoView;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author : CP
 * @version: 1.0
 * @program : BookManage
 * @description : 文本框值改变处理器
 * @date : 2020-07-29 10:51
 **/
@WebServlet("/valueChange")
public class ValueChangeServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("GBK");

        String id = req.getParameter("id");
        Integer price = Integer.valueOf(req.getParameter("price"));

        HttpSession session = req.getSession();

        Map<String, BookInfoView> bookInfoViewMap = (Map<String, BookInfoView>) session.getAttribute("cart");
        BookInfoView bookInfoView = bookInfoViewMap.get(id);

        if(price > 5){
            PrintWriter out = resp.getWriter();
            out.print("<script>alert('商品库存不足!');location.href='shoppingTrolley.jsp';</script>");
            out.flush();
            out.close();
        }else{
            bookInfoView.setAmount(price);
        }

        bookInfoViewMap.put(id,bookInfoView);
        session.setAttribute("cart",bookInfoViewMap);
        resp.sendRedirect("shoppingTrolley.jsp");
    }
}
